<template>
  <div class="booktype">
    <el-row>
      <el-col :span="24">
        <el-button type="primary" @click="onAddBookType">新增分类</el-button>
      </el-col>
    </el-row>
    <el-table :data="tableData" style="width: 100%; margin-top: 20px;">
      <el-table-column prop="booktypeid" label="分类ID" width="100"></el-table-column>
      <el-table-column prop="booktypename" label="分类名称"></el-table-column>
      <el-table-column prop="booktypedesc" label="分类描述"></el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-button size="mini" @click="toUpdateBookType(scope.row)">修改</el-button>
          <el-button size="mini" type="danger" @click="toDelBookType(scope.row.booktypeid)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogVisible"
        width="40%"
        :before-close="handleClose">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px">
        <el-form-item label="分类名称" prop="booktypename">
          <el-input v-model="ruleForm.booktypename"></el-input>
        </el-form-item>
        <el-form-item label="分类描述" prop="booktypedesc">
          <el-input type="textarea" v-model="ruleForm.booktypedesc"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { getbookType, saveOrUpdateBookType, delBookType, validateBookTypeName } from '@/api/api';

export default {
  name: 'BookTypeView',
  data() {
    return {
      tableData: [],
      dialogVisible: false,
      dialogTitle: '',
      ruleForm: {
        booktypeid: null,
        booktypename: '',
        booktypedesc: ''
      },
      rules: {
        booktypename: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { validator: this.checkBookTypeNameUnique, trigger: 'blur' }
        ],
        booktypedesc: [
          { required: true, message: '请输入分类描述', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    // 获取图书分类列表（展示根节点下的所有直接子节点）
    getTreeData() {
      getbookType().then(res => {
        if (res.code === 200 && res.data) {
          // 根节点（booktypeid=8）的 children 才是我们要在表格中展示的直接分类
          this.tableData = res.data.children || [];
        } else {
          this.tableData = [];
        }
      }).catch(err => {
        console.error('获取图书分类失败', err);
        this.$message.error('获取图书分类失败');
      });
    },
    onAddBookType() {
      this.dialogTitle = '新增图书分类';
      this.ruleForm = {
        booktypeid: '', //注意这个地方要初始化为''，如果为null会一直提示文件名称已存在，因为都为null
        booktypename: '',
        booktypedesc: ''
      };
      this.dialogVisible = true;
      // 确保表单验证状态重置
      this.$nextTick(() => {
        this.$refs.ruleForm.clearValidate();
      });
    },
    toUpdateBookType(row) {
      this.dialogTitle = '修改图书分类';
      this.ruleForm = { ...row }; // 复制当前行数据到表单
      this.dialogVisible = true;
      // 确保表单验证状态重置
      this.$nextTick(() => {
        this.$refs.ruleForm.clearValidate();
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          saveOrUpdateBookType(this.ruleForm).then(res => {
            if (res.code === 200) {
              this.$message.success(res.msg || '操作成功');
              this.dialogVisible = false;
              this.getTreeData(); // 刷新列表
            } else {
              this.$message.error(res.msg || '操作失败');
            }
          }).catch(err => {
            console.error('提交失败', err);
            this.$message.error('提交失败，请重试');
          });
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    toDelBookType(booktypeid) {
      this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delBookType(booktypeid).then(res => {
          if (res.code === 200) {
            this.$message.success(res.msg || '删除成功');
            this.getTreeData(); // 刷新列表
          } else {
            this.$message.error(res.msg || '删除失败');
          }
        }).catch(err => {
          console.error('删除失败', err);
          this.$message.error('删除失败，请重试');
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(() => { // 将 _ 替换为 () 或其他表示不使用参数的方式
            done();
          })
          .catch(() => {}); // 将 _ 替换为 () 或其他表示不使用参数的方式
    },
    // 验证分类名称唯一性
    checkBookTypeNameUnique(rule, value, callback) {
      if (!value) {
        return callback(new Error('请输入分类名称'));
      }
      validateBookTypeName(value, this.ruleForm.booktypeid)
          .then(res => {
            if (res.code === 200 && res.data) {
              callback(); // 名称可用
            } else {
              callback(new Error('分类名称已存在')); // 名称已存在
            }
          })
          .catch(err => {
            console.error('验证失败', err);
            callback(new Error('验证失败，请重试'));
          });
    }
  },
  created() {
    this.getTreeData();
  }
};
</script>

<style scoped>
.book-type-view {
  padding: 20px;
}
</style>